/**
 * @Author yinyunqi
 * @date 2018年1月8日
 * @Content 
 */
package com.yongqi.service.console;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.abel533.echarts.Label;
import com.github.abel533.echarts.LabelLine;
import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.axis.AxisLabel;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.SplitLine;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.AxisType;
import com.github.abel533.echarts.code.Magic;
import com.github.abel533.echarts.code.Orient;
import com.github.abel533.echarts.code.PointerType;
import com.github.abel533.echarts.code.RoseType;
import com.github.abel533.echarts.code.SeriesType;
import com.github.abel533.echarts.code.Tool;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.code.X;
import com.github.abel533.echarts.code.Y;
import com.github.abel533.echarts.data.Data;
import com.github.abel533.echarts.feature.MagicType;
import com.github.abel533.echarts.series.Bar;
import com.github.abel533.echarts.series.Line;
import com.github.abel533.echarts.series.Pie;
import com.github.abel533.echarts.style.ItemStyle;
import com.yongqi.mapper.console.BillMapper;
import com.yongqi.mapper.console.DebtMapper;
import com.yongqi.model.Family;
import com.yongqi.model.Member;
import com.yongqi.model.console.Bill;
import com.yongqi.model.console.Debt;
import com.yongqi.pub.DoubleFormat;
import com.yongqi.service.MemberService;

@Service
public class BillService {
    @Autowired
    BillMapper billMapper;
    @Autowired
    DebtMapper debtMapper;
    @Autowired
    MemberService memberService;
    //收入分页查询方法
    public List<Bill> queryBill(Map<String, String> map){
	List<Bill> billList = billMapper.queryBill(map);
	return billList;
    }
    //条件查询方法
    public List<Bill> queryBillByCondition(HashMap<String, String> map){
   	List<Bill> billList = billMapper.queryBillByCondition(map);
   	return billList;
    }
    //分类Echart http://echarts.baidu.com/echarts2/doc/example/line5.html
    public Option Echart() {
	Option option = new Option();
	option.legend("图例组件");
	option.toolbox().show(true).feature(	//工具栏-展示
		Tool.mark,		//辅助线开关
		Tool.dataView,		//数据视图工具，可以展现当前图表所用数据，编辑后可以动态更新
		new MagicType(Magic.line,Magic.bar),	//动态类型切换
		Tool.restore,		//配置项还原
		Tool.saveAsImage);	//保存为图片
	option.calculable(true);	//是否显示拖拽用的手柄
	option.tooltip().trigger(Trigger.item).formatter("{a} <br/>{b} : {c} ({d}%)");//提示组件-触发类型：item数据项图形触发,axis:坐标轴触发
	
	ValueAxis valueAxis = new ValueAxis();		//直角坐标系中的x轴
	valueAxis.axisLabel().formatter("{value} °C");	//x坐标轴刻度设置
	option.xAxis(valueAxis);
	
	CategoryAxis categoryAxis = new CategoryAxis();	//直角坐标系中的x轴
	categoryAxis.axisLine().onZero(false);	//y坐标轴轴线设置，x轴或者y轴的轴线是否在另一个轴的0刻度上，只有在另一个轴为竖直轴且包含0刻度时有效
	categoryAxis.axisLabel().formatter("{value} km");//y轴刻度线设置
	categoryAxis.boundaryGap(false);		//坐标轴两边留白策略
	categoryAxis.data(0,10,20,30,40,50,60,70,80);	//y轴数据
	option.yAxis(categoryAxis);
	
	Line line = new Line();
	line.smooth(true).name("高度(km)与气温(°C)变化关系")	//是否平滑曲线显示
			.data(15, -50, -56.5, -46.5, -22.1, -2.5, -27.7, -55.7, -76.5);
//			.itemStyle().normal().lineStyle().shadowColor("rgba(0,0,0,0.4)");
	option.series(line);
	return option;
    }
    /**
     * X月支出饼图
     * @param month
     * @return
     */
    public Option payPie(String time,String member) {
	Map<String, String> map = new HashMap<String, String>();
	String familyAccount = ((Family) SecurityUtils.getSubject().getPrincipal()).getFamilyaccount();
	map.put("time", time);
	map.put("familyAccount", familyAccount);
	map.put("member", member);
	List<Bill> result = billMapper.payPieSelect(map);
	Double commonPay = 0.00;//日常支出
	Double investPay = 0.00;//投资支出
	Double accidentPay = 0.00;//意外支出
	Double consumePay = 0.00;//消费支出
	Double otherPay = 0.00;//其他支出
	for(Bill bill:result) {
	    if (bill.getType().equals("日常支出")) {
		commonPay += Double.valueOf(bill.getMoney());
	    }
	    else if (bill.getType().equals("投资支出")) {
		investPay += Double.valueOf(bill.getMoney());
	    }
	    else if (bill.getType().equals("意外支出")) {
		accidentPay += Double.valueOf(bill.getMoney());
	    }
	    else if (bill.getType().equals("消费支出")) {
		consumePay += Double.valueOf(bill.getMoney());
	    }
	    else if (bill.getType().equals("其他支出")) {
		otherPay += Double.valueOf(bill.getMoney());
	    }
	}
	ItemStyle itemStyle = new ItemStyle();
	itemStyle.normal().label(new Label().show(false)).labelLine(new LabelLine().show(false));
	Option option = new Option();
	time = time.replace('-', '年');
	if (time.substring(5, 6).equals("0")) {
	    time = time.substring(0,5)+time.substring(6,7);
	}
	option.title().text(time+"月支出").x(X.left);
	option.tooltip().trigger(Trigger.item).formatter("{a} <br/>{b} : {c} ({d}%)");
	option.legend().orient(Orient.horizontal).x(X.center).y(Y.bottom).data("日常支出","投资支出","意外支出","消费支出","其他支出");
	option.toolbox().show(true).feature(
	 		Tool.mark,
			Tool.dataView,
			new MagicType(Magic.pie),
			Tool.restore,
			Tool.saveAsImage);
	option.calculable(true);
	Pie pie = new Pie();
	pie.clockWise(false).name(time+"月支出")
			.radius(20,110).roseType(RoseType.radius)
			.itemStyle(itemStyle)
			.data(new Data("日常支出",commonPay),new Data("投资支出",investPay),new Data("意外支出",accidentPay),new Data("消费支出",consumePay),new Data("其他支出",otherPay));
	option.series(pie);
	return option;
    }
    /**
     * X月收入饼图
     * @param month
     * @return
     */
    public Option incomePie(String time,String member) {
	Map<String, String> map = new HashMap<String, String>();
	String familyAccount = ((Family) SecurityUtils.getSubject().getPrincipal()).getFamilyaccount();
	map.put("time", time);
	map.put("member", member);
	map.put("familyAccount", familyAccount);
	List<Bill> result = billMapper.incomePieSelect(map);
	Double workIncome = 0.00;//劳动收入
	Double finicialIncome = 0.00;//理财收入
	Double otherIncome = 0.00;//其他收入
	for (Bill bill : result) {
	    if (bill.getType().equals("劳动收入")) {
		workIncome += Double.valueOf(bill.getMoney());
	    }else if (bill.getType().equals("理财收入")) {
		finicialIncome += Double.valueOf(bill.getMoney());
	    }else if (bill.getType().equals("其他收入")) {
		otherIncome += Double.valueOf(bill.getMoney());
	    }
	}
	time = time.replace('-', '年');
	if (time.substring(5, 6).equals("0")) {
	    time = time.substring(0,5)+time.substring(6,7);
	}
	ItemStyle itemStyle = new ItemStyle();
	itemStyle.normal().label(new Label().show(false)).labelLine(new LabelLine().show(false));
	Option option = new Option();
	option.title().text(time+"月收入").x(X.left);
	option.tooltip().trigger(Trigger.item).formatter("{a} <br/>{b} : {c} ({d}%)");
	option.legend().orient(Orient.horizontal).x(X.center).y(Y.bottom).data("劳动收入","理财收入","其他收入");
	option.toolbox().show(true).feature(
	 		Tool.mark,
			Tool.dataView,
			new MagicType(Magic.pie),
			Tool.restore,
			Tool.saveAsImage);
	option.calculable(true);
	Pie pie = new Pie();
	pie.clockWise(false).name(time+"月收入")
			.radius("50","70")
			.itemStyle(itemStyle)
			.data(new Data("劳动收入",workIncome),new Data("理财收入",finicialIncome),new Data("其他收入",otherIncome));
	option.series(pie);
	return option;
    }
    /**
     * X月借款饼图
     * @param month
     * @return
     */
    public Option debtPie(String time,String member) {
	Map<String, String> map = new HashMap<String, String>();
	String familyAccount = ((Family) SecurityUtils.getSubject().getPrincipal()).getFamilyaccount();
	map.put("time", time);
	map.put("member", member);
	map.put("familyAccount", familyAccount);
	Double borrowIn = 0.00;
	Double borrowOut = 0.00;
	List<Debt> result = debtMapper.debtPieSelect(map);
	for (Debt debt : result) {
	    if (debt.getDebttype().equals("借入")) {
		borrowIn += Double.valueOf(debt.getMoney());
	    }else if (debt.getDebttype().equals("借出")) {
		borrowOut += Double.valueOf(debt.getMoney());
	    }
	}
	time = time.replace('-', '年');
	if (time.substring(5, 6).equals("0")) {
	    time = time.substring(0,5)+time.substring(6,7);
	}
	ItemStyle itemStyle = new ItemStyle();
	itemStyle.normal().label(new Label().show(false)).labelLine(new LabelLine().show(false));
	Option option = new Option();
	option.title().text(time+"月借款").x(X.left);
	option.tooltip().trigger(Trigger.item).formatter("{a} <br/>{b} : {c} ({d}%)");
	option.legend().orient(Orient.horizontal).x(X.center).y(Y.bottom).data("借入","借出");
	option.toolbox().show(true).feature(
	 		Tool.mark,
			Tool.dataView,
			new MagicType(Magic.pie),
			Tool.restore,
			Tool.saveAsImage);
	option.calculable(true);
	Pie pie = new Pie();
	pie.clockWise(false).name(time+"月借款")
			.radius("55%")
			.itemStyle(itemStyle)
			.data(new Data("借入",borrowIn),new Data("借出",borrowOut));
	option.series(pie);
	return option;
    }
    /**
     * X月各项汇总图
     * @param time
     * @return
     */
    public Option totalBar(String time) {
	List<Double> incomeData = new ArrayList<Double>();
	List<Double> payData = new ArrayList<Double>();
	List<Double> inData = new ArrayList<Double>();
	List<Double> outData = new ArrayList<Double>();
	Double incomeSum = 0.00;
	Double paySum = 0.00;
	Double inSum = 0.00;
	Double outSum = 0.00;
	StringBuffer memberString = new StringBuffer();
	//获取成员List，遍历，获得收入List，获得1-收入List
	String familyAccount = ((Family) SecurityUtils.getSubject().getPrincipal()).getFamilyaccount();
	List<Member> memberList = memberService.echartQueryMember(familyAccount);
	for (Member member : memberList) {
	    memberString.append(member.getMemberName()+'@');
	    Map<String, String> map = new HashMap<String, String>();
	    map.put("time", time);
	    map.put("member", member.getMemberName());
	    //根据遍历获得的成员作为条件查询该成员的收入、支出、借入、借出
	    //收入
	    List<Bill> incomeBill = billMapper.incomePieSelect(map);
	    Double incomeTemp = 0.00;
	    for (Bill bill : incomeBill) {
	    	incomeTemp += Double.valueOf(bill.getMoney());//收入临时变量计算单个成员收入总值，然后存入收入集合中
	    	incomeSum += Double.valueOf(bill.getMoney());
	    }
	    incomeData.add(incomeTemp);
	    //支出
	    List<Bill> payBill = billMapper.payPieSelect(map);
	    Double payTemp = 0.00;
	    for (Bill bill : payBill) {
	    	payTemp += Double.valueOf(bill.getMoney());//收入临时变量计算单个成员收入总值，然后存入收入集合中
	    	paySum += Double.valueOf(bill.getMoney());
	    }
	    payData.add(payTemp);
	    //借入
	    List<Debt> inDebt = debtMapper.inDebt(map);
	    Double inTemp = 0.00;
	    for (Debt debt : inDebt) {
	    	inTemp += Double.valueOf(debt.getMoney());//收入临时变量计算单个成员收入总值，然后存入收入集合中
	    	inSum += Double.valueOf(debt.getMoney());
	    }
	    inData.add(inTemp);
	    //借出
	    List<Debt> outDebt = debtMapper.outDebt(map);
	    Double outTemp = 0.00;
	    for (Debt debt : outDebt) {
	    	outTemp += Double.valueOf(debt.getMoney());//收入临时变量计算单个成员收入总值，然后存入收入集合中
	    	outSum += Double.valueOf(debt.getMoney());
	    }
	    outData.add(outTemp);
	}
	//对收入结果拼接放入bar
	StringBuffer incomeDataResult = new StringBuffer();
	StringBuffer incomeDataResult2 = new StringBuffer();
	for(int i=0;i<incomeData.size();i++) {
		if (incomeSum == 0 || incomeSum == null) {
			incomeDataResult.append(0.00).append("@");
			incomeDataResult2.append(0.00).append("@");
		}else {
		    incomeDataResult.append(DoubleFormat.format1(Double.valueOf(incomeData.get(i)/incomeSum*100))).append("@");
		    incomeDataResult2.append(DoubleFormat.format1(Double.valueOf((1-incomeData.get(i)/incomeSum))*100)).append("@");
		}
	}
	//对支出结果拼接
	StringBuffer payDataResult = new StringBuffer();
	StringBuffer payDataResult2 = new StringBuffer();
	for(int i=0;i<payData.size();i++) {
		if (paySum == 0 || paySum == null) {
			payDataResult.append(0.00).append("@");
			payDataResult2.append(0.00).append("@");
		}else {
			payDataResult.append(DoubleFormat.format1(Double.valueOf(payData.get(i)/paySum*100))).append("@");
			payDataResult2.append(DoubleFormat.format1(Double.valueOf((1-payData.get(i)/paySum))*100)).append("@");
		}
	}
	//对借入结果拼接
	StringBuffer inDataResult = new StringBuffer();
	StringBuffer inDataResult2 = new StringBuffer();
	for(int i=0;i<inData.size();i++) {
		if (inSum == 0 || inSum == null) {
			inDataResult.append(0.00).append("@");
			inDataResult2.append(0.00).append("@");
		}else {
			inDataResult.append(DoubleFormat.format1(Double.valueOf(inData.get(i)/inSum*100))).append("@");
	 		inDataResult2.append(DoubleFormat.format1(Double.valueOf((1-inData.get(i)/inSum))*100)).append("@");
		}
	}
	//对借出结果拼接
	StringBuffer outDataResult = new StringBuffer();
	StringBuffer outDataResult2 = new StringBuffer();
	for(int i=0;i<outData.size();i++) {
		if (outSum == 0 || outSum == null) {
			outDataResult.append(0.00).append("@");
			outDataResult2.append(0.00).append("@");
		}else {
			outDataResult.append(DoubleFormat.format1(Double.valueOf(outData.get(i)/outSum*100))).append("@");
			outDataResult2.append(DoubleFormat.format1(Double.valueOf((1-outData.get(i)/outSum))*100)).append("@");
		}
	}
	time = time.replace('-', '年');
	if (time.substring(5, 6).equals("0")) {
	    time = time.substring(0,5)+time.substring(6,7);
	}
	ItemStyle itemStyle = new ItemStyle();
	itemStyle.normal().label().show(true).position("insideLeft").formatter("{c}%");
	ItemStyle placeHoledStyle= new ItemStyle();
	placeHoledStyle.normal().barBorderColor("rgba(0,0,0,0)").color("rgba(0,0,0,0)");
	placeHoledStyle.emphasis().barBorderColor("rgba(0,0,0,0)").color("rgba(0,0,0,0)");
	Option option = new Option();
	String family = "";
	option.title(time+"月各项汇总","From Family"+family);
	option.tooltip().trigger(Trigger.axis).formatter("{b}<br/>{a0}:{c0}%<br/>{a2}:{c2}%<br/>{a4}:{c4}%<br/>{a6}:{c6}%");
	option.tooltip().axisPointer().type(PointerType.shadow);
	option.legend().orient(Orient.horizontal).x(X.center).y(Y.bottom).itemGap(58).data("收入","支出","借入","借出");
	option.toolbox().show(true).feature(
			Tool.mark,
			Tool.dataView,
			Tool.restore,
			Tool.saveAsImage
		);
	option.grid().y(80).y2(30);
	option.xAxis(new ValueAxis().type(AxisType.value).position("bottom").show(true)
		.splitLine(new SplitLine().show(false))
		.axisLabel(new AxisLabel().show(false))
		);
//	memberString.delete(0,1);
	memberString.delete(memberString.length()-1,memberString.length());
	option.yAxis(new CategoryAxis().type(AxisType.category)
		.splitLine(new SplitLine().show(false))
		.data(memberString)
		);
	Bar bar = new Bar();
	bar.name("收入").type(SeriesType.bar).stack("总量").data(incomeDataResult);
	bar.itemStyle().normal().label().show(true).position("insideLeft").formatter("{c}%");
	Bar bar2 = new Bar();
	bar2.name("收入").type(SeriesType.bar).stack("总量").data(incomeDataResult2);
	bar2.itemStyle().normal().barBorderColor("rgba(0,0,0,0)").color("rgba(0,0,0,0)");
	bar2.itemStyle().emphasis().barBorderColor("rgba(0,0,0,0)").color("rgba(0,0,0,0)");
	Bar bar3 = new Bar();
	bar3.name("支出").type(SeriesType.bar).stack("总量").data(payDataResult);
	bar3.itemStyle().normal().label().show(true).position("insideLeft").formatter("{c}%");
	Bar bar4 = new Bar();
	bar4.name("支出").type(SeriesType.bar).stack("总量").data(payDataResult2);
	bar4.itemStyle().normal().barBorderColor("rgba(0,0,0,0)").color("rgba(0,0,0,0)");
	bar4.itemStyle().emphasis().barBorderColor("rgba(0,0,0,0)").color("rgba(0,0,0,0)");
	Bar bar5 = new Bar();
	bar5.name("借入").type(SeriesType.bar).stack("总量").data(inDataResult);
	bar5.itemStyle().normal().label().show(true).position("insideLeft").formatter("{c}%");
	Bar bar6 = new Bar();
	bar6.name("借入").type(SeriesType.bar).stack("总量").data(inDataResult2);
	bar6.itemStyle().normal().barBorderColor("rgba(0,0,0,0)").color("rgba(0,0,0,0)");
	bar6.itemStyle().emphasis().barBorderColor("rgba(0,0,0,0)").color("rgba(0,0,0,0)");
	Bar bar7 = new Bar();
	bar7.name("借出").type(SeriesType.bar).stack("总量").data(outDataResult);
	bar7.itemStyle().normal().label().show(true).position("insideLeft").formatter("{c}%");
	Bar bar8 = new Bar();
	bar8.name("借出").type(SeriesType.bar).stack("总量").data(outDataResult2);
	bar8.itemStyle().normal().barBorderColor("rgba(0,0,0,0)").color("rgba(0,0,0,0)");
	bar8.itemStyle().emphasis().barBorderColor("rgba(0,0,0,0)").color("rgba(0,0,0,0)");
	option.series(bar,bar2,bar3,bar4,bar5,bar6,bar7,bar8);
	return option;
    }
    /**
     * 绘制地图踪迹图
     * @param map
     * @return
     */
    public List<Bill> payPathMap(Map<String, String> map){
	return billMapper.payPathMap(map);
    }
    /**
     * 后台-收入查询
     * @param map
     * @return
     */
    public List<Bill> backIncomeQuery(Map<String, String> map) {
	return billMapper.backBillQuery(map);
    }
    /**
     * 后台-收入删除
     * @param map
     * @return
     */
    public void backIncomeDeleteById(Map<String, String> map) {
	 billMapper.backBillDeleteById(map);
    }
    /**
     * 后台-收入查询
     * @param map
     * @return
     */
    public List<Bill> backPayQuery(Map<String, String> map) {
	return billMapper.backBillQuery(map);
    }
    /**
     * 后台-收入删除
     * @param map
     * @return
     */
    public void backPayDeleteById(Map<String, String> map) {
	 billMapper.backBillDeleteById(map);
    }
    
    public List<Bill> queryPageItems(Map<String, String> map) {
    	return billMapper.queryPageItems(map);
    }
}

